package com.megvii.koala.tv.presenter;

import android.widget.Toast;

import com.megvii.corelib.net.Callback;
import com.megvii.corelib.util.AppUtil;
import com.megvii.koala.base.KoalaPresenter;
import com.megvii.koala.constance.ErrorCode;
import com.megvii.koala.tv.data.CameraBean;
import com.megvii.koala.tv.data.SurveillanceCameraManager;
import com.megvii.koala.tv.data.TVBoxManager;
import com.megvii.koala.tv.data.TVGlobalData;
import com.megvii.koala.tv.event.ScreenConfigCompleteEvent;
import com.megvii.koala.tv.fragment.DisplayCameraSettingFragment;
import com.megvii.koala.tv.net.TVNetAPI;
import com.megvii.koala.tv.net.tv.SetDisplayConfigResponse;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by linyue on 16/3/16.
 */
public class DisplayCameraSettingPresenter extends KoalaPresenter<DisplayCameraSettingFragment>
        implements DisplayCameraSettingFragment.DisplayCameraSettingListener {
    private SurveillanceCameraManager cameraManager;

    private TVBoxManager boxManager;

    @Override
    protected void onCreated() {
        super.onCreated();
        this.cameraManager = TVGlobalData.instance().cameraManager;
        this.boxManager = TVGlobalData.instance().boxManager;
        viewHolder.setListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Collection<CameraBean> recognizeCameras = cameraManager.getRecognizeCameras();
        List<CameraBean> list = new ArrayList<>();
        list.addAll(recognizeCameras);
        viewHolder.updateView(list);
    }

    @Override
    public void onClickSave(CameraBean camera) {
        cameraManager.setPreviewCamera(camera);
        String boxToken = boxManager.getSelectedToken();
        String deviceToken = AppUtil.getDeviceUUID(viewHolder.getActivity());
        List<Integer> screens = new ArrayList<>();
        Collection<CameraBean> recognizeCameras = cameraManager.getRecognizeCameras();
        for (CameraBean recognizeCamera : recognizeCameras) {
            screens.add(Integer.valueOf(recognizeCamera.id));
        }
        CameraBean previewCamera = cameraManager.getPreviewCamera();
        viewHolder.showProgressBar();
        TVNetAPI.requestSetDisplayConfig(boxToken, deviceToken, screens,
                Integer.valueOf(previewCamera.id), this, this);
    }

    @Callback(clazz = SetDisplayConfigResponse.class)
    public void onSetDisplayConfigResponse(SetDisplayConfigResponse response) {
        viewHolder.hideProgressBar();
        if (response.code == ErrorCode.NO_ERROR) {
            viewHolder.finishFragments();
            cameraManager.persistentSave();
            EventBus.getDefault().post(new ScreenConfigCompleteEvent());
        } else {
            showToast(ErrorCode.getDescription(response.code));
        }
    }

    @Override
    public void onBackPressed() {
        viewHolder.finish();
    }
}
